//
//  WBBaseViewController.swift
//  传智微博
//
//  Created by zhoujiming on 2016/12/15.
//  Copyright © 2016年 gmcc. All rights reserved.
//

import UIKit

// class WBBaseViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
class WBBaseViewController: UIViewController{
    
    //var userLogon = true
    
    var visitorInfoDictionary: [String : String]?
    
    // 如果用户没登陆，则不加载
    var tableView: UITableView?
    
    var isPullup = false
    // 刷新控件
    var refreshControl: CZRefreshControl?
    lazy var navigationBar = UINavigationBar(frame : CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    
    lazy var navItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        WBNetworkManager.shared().userLogon ? loadData() : ()
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: WBUserLogonSuccessNotification), object: nil)
    }
    
    deinit{
        
        NotificationCenter.default.removeObserver(self)
    }
    
    override var title: String?{
        didSet{
            navItem.title = title
        }
    }
    
    func loadData(){
        refreshControl?.endRefreshing()
    }
}
// MARK: - 访客视图监听方法
extension WBBaseViewController{
    @objc fileprivate func loginSuccess(n:Notification){
        print("登录成功\(n)")
        // 重置导航栏的左右按钮
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        // 更新ui---重设view
        // 在访问view的getter时，如果view==nil，回调用loadview-》viewDidLoad
        view = nil
        
        // 注销通知，重新执行viewDidLoad会重新注册通知！避免重复注册
        NotificationCenter.default.removeObserver(self)
    }
    @objc fileprivate func login(){
        //print("用户登录")
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLogonNotification), object: nil)
    }
    
    @objc fileprivate func register(){
        print("用户注册")
    }
}

// MARK: - 设置界面/Users/zhoujm/Documents/Develop/SwiftWorkSpace/Weibo/传智微博/传智微博/Classes/View/Main/WBBaseViewController.swift:15:9: 'setupUI' is inaccessible due to 'private' protection level
extension WBBaseViewController{
    fileprivate func setupUI()
    {
        view.backgroundColor = UIColor.white
        
        automaticallyAdjustsScrollViewInsets = false
        
        setNavigationBar()
        
        WBNetworkManager.shared().userLogon ? setupTableView() : setupVisitorView()
    }
    
    func setupTableView(){
        tableView = UITableView(frame: view.bounds, style: .plain)
        
        view.addSubview(tableView!)
        
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        // 设置数据源河代理
        tableView?.dataSource = self
        tableView?.delegate = self
        
        tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        
        // 修改指示器的缩进
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        // 设置刷新控件
        refreshControl = CZRefreshControl()
        // 添加到视图
        tableView?.addSubview(refreshControl!)
        
        // 添加事件监听方法
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
    }
    
    private func setupVisitorView(){
        let visitorView = WBVisitorView(frame: view.bounds)
        
        view.insertSubview(visitorView, belowSubview: navigationBar)
        
        visitorView.visitorInfo = visitorInfoDictionary
        
        // 添加监听方法
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        // 设置导航条按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
        
    }
    private func setNavigationBar(){
        view.addSubview(navigationBar)
        
        navigationBar.items = [navItem]
        
        navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        
        navigationBar.tintColor = UIColor.darkGray
        
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray]

        navigationBar.tintColor = UIColor.orange
    }
}

extension WBBaseViewController: UITableViewDataSource, UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 10
    }
    
    // 在显示最后一行的时候做上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        
        if(row < 0 || section < 0)
        {
            return
        }
        
        let count = tableView.numberOfRows(inSection: section)
        
        if row == count - 1 && !isPullup{
            print("上拉刷新")
            isPullup = true
            
            loadData()
            
        }
    }
}
